package cn.com.bluemoon.daps.system.controller.api;

import cn.com.bluemoon.daps.api.sys.RemoteSystemInfoService;
import cn.com.bluemoon.daps.common.annotation.FcApiFor;
import cn.com.bluemoon.daps.common.constant.ServiceNameConstants.DapsApiSystem;
import cn.com.bluemoon.daps.common.datascope.IgnorePermission;
import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.common.enums.BmStatus;
import cn.com.bluemoon.daps.common.enums.SystemType;
import cn.com.bluemoon.daps.system.dto.SystemInfoDto;
import cn.com.bluemoon.daps.system.entity.DapSystemInfo;
import cn.com.bluemoon.daps.system.mapper.DapSystemInfoMapper;
import cn.com.bluemoon.daps.system.service.DapSystemInfoService;
import cn.com.bluemoon.daps.system.vo.SimpleSysInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

@Api(tags = {"FeignClient服务-系统api接口"})
@RequestMapping(DapsApiSystem.API_SYSINFO)
@IgnorePermission(name = "服务注册-系统api接口")
@RestController
@Slf4j
public class DapSystemInfoApi implements RemoteSystemInfoService {

    @Resource
    DapSystemInfoService dapSystemInfoService;

    /**
     * 根据系统id获取系统信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResultBean<DapSystemInfo> getSystemInfo(@PathVariable("id") String id) {

        DapSystemInfo sysById = dapSystemInfoService.getSysById(id);
        return ResultBean.ok(sysById);
    }

    @Override
    @PostMapping("/getSystemInfoList")
    public ResultBean<List<DapSystemInfo>> getSystemInfoList(String ids) {

        List<DapSystemInfo> list = dapSystemInfoService.list(new LambdaQueryWrapper<DapSystemInfo>()
                .eq(DapSystemInfo::getBmStatus, BmStatus.ON.getCode()).in(DapSystemInfo::getId, Lists.newArrayList(ids.split(","))));
        return ResultBean.ok(list);
    }

    /**
     * 元数据调用
     *
     * @return
     */
    @PostMapping("/list")
    @FcApiFor(team = "数据资产团队")
    public ResultBean<List<DapSystemInfo>> getSysInfos(@RequestParam(value = "name", required = false) String name) {

        List<DapSystemInfo> list = dapSystemInfoService.list(new LambdaQueryWrapper<DapSystemInfo>()
                .eq(DapSystemInfo::getBmStatus, BmStatus.ON.getCode()));
        if (StringUtils.isNotBlank(name)) {
            List<DapSystemInfo> collect = list.stream().filter(l -> l.getName()
                    .contains(name)).collect(Collectors.toList());
            return ResultBean.ok(collect);
        }
        return ResultBean.ok(list);
    }

    @PostMapping("/page")
    public Page<SystemInfoDto> getSysInfoPage(@RequestParam("current") Long current,
                                       @RequestParam("pageSize") Long pageSize,
                                       @RequestParam(value = "keyword", required = false) String keyword,
                                       @RequestParam("bmStatus") BmStatus bmStatus) {
        Page mpPage = new Page();
        mpPage.setCurrent(current);
        mpPage.setSize(pageSize);
        Page<SystemInfoDto> sysInfoPage = dapSystemInfoService.getBaseMapper(DapSystemInfoMapper.class)
                .getSysInfoPage(mpPage, keyword, bmStatus.getCode());
        return sysInfoPage;
    }

    @ApiOperation("获取系统信息")
    @GetMapping("/get")
    public Optional<DapSystemInfo> getById(@RequestParam("id") String sysId) {
        return dapSystemInfoService.getCacheOneById(sysId);
    }

    @PutMapping("/auditStatus")
    public ResultBean<Boolean> updateAuditStatusById(@RequestParam("status") Integer auditStatus,
                                              @RequestParam(value = "auditResultId", required = false, defaultValue = "") String auditResultId,
                                              @RequestParam("updateAuditTime") boolean updateAuditTime,
                                              @RequestParam("sysId") String systemId) {
        UpdateWrapper<DapSystemInfo> where = dapSystemInfoService.bmUpdate().set("audit_status", auditStatus)
                .set(updateAuditTime, "audit_time", LocalDateTime.now())
                .set(isNotBlank(auditResultId), "audit_result_id", auditResultId)
                .eq("id", systemId);
        boolean update = dapSystemInfoService.update(where);
        return ResultBean.ok(update);
    }

    @GetMapping("/user/sysInfo")
    @FcApiFor(team = {"IT中心/技术研发部/供应链研发团队/SCM开发组", "数据资产团队"})
    public ResultBean<List<SimpleSysInfoVo>> getSystemInfosByUserIdAndType(@RequestParam(value = "userId") String userId,
                                                                           @RequestParam(value = "userType", required = false,
                                                                                   defaultValue = "2") Integer userType) {
        List<SystemInfoDto> infos = dapSystemInfoService.getSystemInfosByUserIdAndType(userId, userType);
        return ResultBean.ok(infos).convert(s -> s.stream()
                .map(d -> new SimpleSysInfoVo(d.getDapSystemInfo()))
                .collect(Collectors.toList()));
    }

    /**
     * 根据指定数据库类型获取简易系统信息列表
     *
     * @param dbType 1 mysql, 2 pgsql, 3 hive,... etc.
     * @return result
     * @see cn.com.bluemoon.daps.common.enums.DatabaseType
     * @see SystemType
     */
    @GetMapping("/system/dbType")
    @FcApiFor(team = {"数据资产团队"})
    public ResultBean<List<SimpleSysInfoVo>> listByDbType(@RequestParam(value = "dbType") Integer dbType){
        List<SimpleSysInfoVo> sysInfoVos = dapSystemInfoService.listByDbType(dbType);
        return ResultBean.ok(sysInfoVos);
    }

    @Override
    public ResultBean<DapSystemInfo> getSysInfo(String name) {
        DapSystemInfo res = dapSystemInfoService.getOne(dapSystemInfoService.bmLambdaQuery().eq(DapSystemInfo::getName, name).last(" limit 1"));
        return ResultBean.ok(res);
    }

}
